package cn.topevery.garden.framework.util;

import cn.topevery.garden.framework.config.RsaKeyProperties;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * KeyUtils
 *
 * @author wilson.fu
 * @date 2022/8/25 10:20
 */
public final class KeyUtils {

    public static SecretKey generateSecretKey() {
        SecretKey hmacKey;
        try {
            hmacKey = KeyGenerator.getInstance("HmacSha256").generateKey();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return hmacKey;
    }

    public static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

    public static KeyPair generateRsaKey(RsaKeyProperties rsaKeyProperties) {
        if(rsaKeyProperties == null || StringUtils.isEmpty(rsaKeyProperties.getPublicKey()) || StringUtils.isEmpty(rsaKeyProperties.getPrivateKey())){
            return generateRsaKey();
        }

        KeyPair keyPair;
        try {
            RSAPublicKey publicKey = loadPublicKeyByStr(rsaKeyProperties.getPublicKey());
            RSAPrivateKey privateKey = loadPrivateKeyByStr(rsaKeyProperties.getPrivateKey());
            keyPair = new KeyPair(publicKey, privateKey);
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }


    /**
     * 私玥解密
     * @param privateKey
     * @param cipherData
     * @return
     */
    public static byte[] decrypt(PrivateKey privateKey, byte[] cipherData) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] output = cipher.doFinal(cipherData);
        return output;
    }

    /**
     * 私玥解密
     * @param privateKey
     * @param cipherStr
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(PrivateKey privateKey, String cipherStr) throws Exception {
        return decrypt(privateKey, Base64.decodeBase64(cipherStr));
    }

    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }
}
